package com.iwunu.gateway.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.config.UrlConfig;
import com.iwunu.gateway.constant.ApartmentConstant;
import com.iwunu.gateway.entity.FLockMember;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.FacesLogMongodbService;
import com.iwunu.gateway.service.FlockLogService;
import com.iwunu.gateway.service.ImageFeatureService;
import com.iwunu.gateway.service.ImageMongodbService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.util.ComUtil;
import com.iwunu.gateway.util.FeatureSoUtil;
import com.iwunu.gateway.util.FileUtils;
import com.iwunu.gateway.util.PitNumUtil;
import com.iwunu.gateway.vo.CmdIssuedLineVo;
import com.iwunu.gateway.vo.CmdIssuedVo;
import com.iwunu.gateway.vo.LogVo;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.constant.Constant;
import com.iwunu.iot.common.constant.ResultCodeEnum;
import com.iwunu.iot.common.util.HexUtils;
import com.iwunu.iot.common.util.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RequestMapping("/fackLock/admin")
@Controller
@Api(value = "/fackLock/admin", tags = "人脸锁后台控制层接口", description = "人脸锁后台控制层接口")
public class FacesLockAdminController {
	@Autowired
	public RedisService redisService;
	@Autowired
	public FaceLockService faceLockService;
	@Autowired
	public FlockLogService flockLogService;
	@Autowired
	private ImageMongodbService imageMongodbService;
	@Autowired
	private CmdIssuedMongodbService cmdIssuedMongodbService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private FaceLockMemberService faceLockMemberService;
	@Autowired
	private ImageFeatureService imageFeatureService;
	@Autowired
	private UrlConfig urlConfig;

	@Autowired
	private FacesLogMongodbService facesLogMongodbService;
	private static final String fileUploadPath = "/opt/img";

	/**
	 ** 下发密码
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/password/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cmdIssued(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId.longValue());
		if (StringUtils.isEmpty(bussinessNo) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, bussinessNo, flock.getClientId(),
				ClientOpenTypeEnum.PASSWORD.getType(), 1);
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.OVER_PITNUM.getCode(), ResultCodeEnum.OVER_PITNUM.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
				null);
		result.setPitNum(code);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 下发卡号
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/cardNo/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cardNo(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId")  Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId.longValue());
		if (StringUtils.isEmpty(bussinessNo) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, bussinessNo, flock.getClientId(),
				ClientOpenTypeEnum.CARD.getType(), 1);
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
				null);
		result.setPitNum(code);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}


	/**
	 ** 下发指纹
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/finger/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> finger(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody List<CmdIssuedVo> cmdIssuedVos) {
		Result result = null;
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId.longValue());
		if (StringUtils.isEmpty(bussinessNo) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String code = cmdIssuedMongodbService.saveSendImageData(cmdIssuedVos, bussinessNo, flock.getClientId(),
				ClientOpenTypeEnum.FINGER.getType(), 1);
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
				null);
		result.setPitNum(code);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	/**
	 ** 人脸图像下发
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/facesImage/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> uploadThumbnail(@RequestHeader String Authorization,
			@RequestParam("facesImage") MultipartFile[] multipartFiles,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "备注", required = true) @RequestParam("remark") String remark,
			@ApiParam(value = "有效开始时间", required = true) @RequestParam("startTime") String startTime,
			@ApiParam(value = "有效结束时间", required = true) @RequestParam("endTime") String endTime) throws Exception {

		Result result = null;
		Integer type = 1;
		byte[] imageData =  null;
		byte[] imageDataFeature = null;
		Integer pitNum = null;
		JSONObject json = new JSONObject();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		FaceLock lock = faceLockService.getFaceLockByUUID(Long.parseLong(lockId.toString()));
		List<ImageMongo> images = imageMongodbService.getSendImageData(flock.getLockClientId());
		if (images.size() > ApartmentConstant.imagePitNum) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}

		if (!ComUtil.isEmpty(multipartFiles) && multipartFiles.length != 0) {
			for (MultipartFile multipartFile : multipartFiles) {
				pitNum = PitNumUtil.getImagePitNum(images);
				String postFix = multipartFile.getOriginalFilename()
						.split("//.")[multipartFile.getOriginalFilename().split("//.").length - 1];
				if (Arrays.asList(Constant.FilePostFix.IMAGES).contains(postFix)) {
					result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(),
							ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
					return new ResponseEntity<>(result, HttpStatus.OK);
				}
				String url = FileUtils.fileSave(multipartFile.getInputStream(), 1, multipartFile.getOriginalFilename(),
						null);
				String preUrl = FileUtils.thumbnails(url, url);
				if (StringUtils.isEmpty(preUrl)) {
					result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(),
							ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
					return new ResponseEntity<>(result, HttpStatus.OK);
				}
				if(lock.getIsNewLock()) {
					json = FeatureSoUtil.invoke(preUrl);
					type = ClientOpenTypeEnum.FM226FEATURE.getType();
					imageDataFeature = json.getString("data").getBytes();
				}else if(!lock.getIsNewLock()) {
					type = ClientOpenTypeEnum.FACES.getType();
					imageDataFeature = imageFeatureService.getImageFeature(multipartFile.getBytes());
					if (imageDataFeature == null) {
						result = new Result(ResultCodeEnum.CMDISSUED_FAIL.getCode(),
								ResultCodeEnum.CMDISSUED_FAIL.getDesc(), null);
						return new ResponseEntity<>(result, HttpStatus.CREATED);
					}
					String data = HexUtils.bytesToHexString(imageDataFeature, imageDataFeature.length);
					imageData = FileUtils.getImageFromLocalByUrl(preUrl);
					preUrl = urlConfig.getImageHost() + preUrl.replace(fileUploadPath, "");
					json.put("feature", data);
					json.put("size", imageData.length);

				}
					preUrl = urlConfig.getImageHost() + preUrl.replace(fileUploadPath, "");
					ImageMongo imageMongo = imageMongodbService.saveSendImageData(startTime, endTime, imageData,imageDataFeature, userId,
						pitNum, preUrl, flock.getLockClientId(), flock.getRole(), remark);
					json.put("flDeviceId", flock.getLockClientId());
					json.put("clientId", flock.getLockClientId());
					json.put("pitNum", pitNum);
					json.put("startTime", startTime);
					json.put("endTime", endTime);
					redisService.rightPush(flock.getLockClientId() + "##_" + type, json.toJSONString());
					redisService.rightPush(flock.getLockClientId() + "##_" + ClientOpenTypeEnum.FACES.getType(), json.toJSONString());
//					FileUtils.deleteFile(url);
				}
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
				null);
		result.setPitNum(pitNum==null?"":pitNum.toString());
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	
	/**
	 ** 人脸图像修改下发
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/updateFace/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> updateFace(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "坑号", required = true) @RequestParam("pitNum") Integer pitNum,
			@ApiParam(value = "有效开始时间", required = true) @RequestParam("startTime") String startTime,
			@ApiParam(value = "有效结束时间", required = true) @RequestParam("endTime") String endTime) throws Exception {
		Result result = null;
		Integer type = ClientOpenTypeEnum.FACES.getType();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String delKey = flock.getClientId() + ClientOpenTypeEnum.DELFACES.getData();
		ImageMongo image = imageMongodbService.getImageByDeviceId(flock.getClientId(), pitNum);
		redisService.rightPush(delKey, pitNum.toString());
		imageMongodbService.updateImage(flock.getClientId(), pitNum, endTime, startTime);
		JSONObject json = new JSONObject();
		json.put("flDeviceId", flock.getClientId());
		json.put("clientId", flock.getClientId());
		json.put("pitNum", pitNum);
		json.put("size", image.getImageData().length);
		json.put("startTime", startTime);
		json.put("endTime", endTime);
		redisService.rightPush(flock.getClientId() + "##_" + type, json.toJSONString());
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS_ADMIN.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 开锁
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/openLock/{lockId}/{status}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> openLock(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "开门转态1:开门后常开0:开门", required = true) @PathVariable("status") Integer status) {
		Result result = null;
		String type = ClientOpenTypeEnum.OPEN.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + type;
		if (redisService.get(key) == null) {
			redisService.setex(key, 120, status.toString());
			flockLogService.saveLog(bussinessNo, status.toString(), flock.getClientId(), lockId,
					ClientOpenTypeEnum.OPEN.getType(),1);
		}
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除密码
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/delPwd/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delPwd(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "坑号", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELPWD.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		List<String> sendData = redisService.getList(key);
		for(String data:sendData) {
			System.out.println("redis delPwd+++++++++++++++:"+data);
		}
		cmdIssuedMongodbService.updateCmd(flock.getClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除卡
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/delCard/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delCard(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "坑号", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELCARD.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除指纹
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/delFinger/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delFinger(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "坑号", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELFINGER.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除人脸
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/delFaces/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delFaces(@RequestHeader String bussinessNo,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "坑号", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELFACES.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + type;
		System.out.println("delFaces + pitNum:" + pitNum);
		ImageMongo imageMongo = imageMongodbService.getImageByDeviceId(flock.getClientId(), pitNum);
		redisService.rightPush(key, pitNum.toString());
		imageMongodbService.updateImage(imageMongo.getClientId(), pitNum);
//        FileUtils.deleteFile(imageMongo.getImageUrl());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 清除开锁信息
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/clear/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> clear(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		String typepwd = ClientOpenTypeEnum.DELPWD.getData();
		String typecard = ClientOpenTypeEnum.DELCARD.getData();
		String typefingle = ClientOpenTypeEnum.DELFINGER.getData();
		String typefaces = ClientOpenTypeEnum.DELFACES.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + typepwd;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typecard;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typefingle;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typefaces;
		redisService.rightPush(key, ApartmentConstant.imagePitNum.toString());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 获取用户人脸
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/facesList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> facesList(@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("currentPage") Integer currentPage,
			@RequestParam(value = "name", required = false) String name,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId) {
		Result result = null;
		FaceLock flock = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
		if (StringUtils.isEmpty(bussinessNo) || flock == null ) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		 Map<String, Object>  userCmdIssueds = faceLockService.getAdminImageData(flock.getClientId(),  currentPage, pageSize, name);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 获取用户密码
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/passwordList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> passwordList(@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "name", required = false) String name,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.PASSWORD.getType();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null ) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		Map<String, Object> userCmdIssueds = faceLockService.getAdminCmdIssude(flock.getId(),flock.getClientId(), currentPage,pageSize,type,name);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 获取用户房卡
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/cardList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cardList(@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "name", required = false) String name,		
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.PASSWORD.getType();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null ) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		Map<String, Object>  userCmdIssueds = faceLockService.getAdminCmdIssude(flock.getId(),flock.getClientId(), currentPage,pageSize,type,name);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 获取用户指纹
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/fingleList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> fingleList(@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "name", required = false) String name,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.FINGER.getType();
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (StringUtils.isEmpty(bussinessNo) || flock == null ) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		Map<String, Object> userCmdIssueds = faceLockService.getAdminCmdIssude(flock.getId(),flock.getClientId(), currentPage,pageSize,type,name);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 获取用户人脸
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/loglist/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> loglist(@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime ", required = false) String endTime,
			@RequestParam(value = "openType", required = false) Integer openType,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId) {
		Result result = null;
		LogVo log = new LogVo();
		log.setCurrentPage(currentPage);
		log.setStartTime(startTime);
		log.setEndTime(endTime);
		log.setPageSize(pageSize);
		log.setType(openType);
		Map<String, Object> logs = null;
		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
		if (flock == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		logs = facesLogMongodbService.getAllLog(lockId.intValue(),flock.getClientId(), log);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), logs);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}


	/**
	 ** 保存日志(蓝牙开门)
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/log/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> log(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null || fl.isEmpty()) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		flockLogService.saveBleLog(userId, "10", lockId.toString(), 10, Integer.valueOf(fl.get("role").toString()));
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	public static void main(String[] args) {
		String url = "/opt/img/20210629/1624937036334.jpg";
		System.out.println(url.replace(url.subSequence(0, url.lastIndexOf("/")), ""));
	}

	/**
	 ** 删除下发开锁信息
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/delCmd/{lockId}/{pitNum}/{type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delCmd(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑号", required = true) @PathVariable("pitNum") Integer pitNum,
			@ApiParam(value = "类型", required = true) @PathVariable("type") Integer type// 7密码，8卡，6指纹
	) {
		Result result = null;
		if (type == 7) {
			String fun = ClientOpenTypeEnum.DELCARD.getData();
			String userId = tokenService.parseToken(Authorization);
			FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
			if (StringUtils.isEmpty(Authorization) || flock == null) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String key = flock.getLockClientId() + fun;
			redisService.rightPush(key, pitNum.toString());
			cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		} else {
			String fun = ClientOpenTypeEnum.DELCARD.getData();
			String userId = tokenService.parseToken(Authorization);
			FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
			if (StringUtils.isEmpty(Authorization) || flock == null) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String key = flock.getLockClientId() + fun;
			redisService.rightPush(key, pitNum.toString());
			cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
	}
	
	 /**
     * *锁列表
     * @param Authorization
     * @return
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/lockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> iotlockList(
    		@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage
    		){
    	 Result result = null ;
    	 Map<String, Object> resultMap = faceLockMemberService.selectByAdminFaceLocks(bussinessNo,pageSize,currentPage,null);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),resultMap);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
	 /**
     * *锁列表
     * @param Authorization
     * @return
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/lockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockList(
    		@RequestHeader String bussinessNo,
			@ApiParam(value = "每页显示数量", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "当前页", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "name", required = false) String name
    		){
    	 Result result = null ;
    	 if(StringUtils.isNoneBlank(bussinessNo)) {
     		 result = new Result(ResultCodeEnum.NOT_BUSSINESS_USER.getCode(), ResultCodeEnum.NOT_BUSSINESS_USER.getDesc(),null);
           	 return new ResponseEntity<>(result, HttpStatus.EXPECTATION_FAILED);
    	 }
    	 
    	 Map<String, Object> resultMap = faceLockMemberService.selectByAdminFaceLocks(bussinessNo,pageSize,currentPage,name);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),resultMap);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
	/**
	 ** 远程OTA
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/iot/ota", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> ota(@RequestHeader String Authorization,
			@RequestParam("otaBin") MultipartFile multipartFile,
			@ApiParam(value = "版本号", required = true) @RequestParam("version") String version) {
		Result result = null;
		JSONObject sendData = new JSONObject();
		try {
			String url = FileUtils.fileSave(multipartFile.getInputStream(), 2, multipartFile.getOriginalFilename(),
					null);

			if (StringUtils.isEmpty(Authorization)) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String clientId = tokenService.parseDeviceToken(Authorization);
			Integer vs = Integer.parseInt(version.replaceAll("\\D", ""));
			String type = ClientOpenTypeEnum.OTA.getData();
			sendData.put("md5Str", type);
			sendData.put("data", url);
			sendData.put("md5Str", clientId);
			sendData.put("version", vs);
			sendData.put("packSize", multipartFile.getSize() / 2);
			redisService.set(clientId + type, sendData.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
}
